<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择公司"
          filterable
          clearable
        >
          <el-option
            v-for="option in companyList"
            :key="option.id"
            :label="option.companyName"
            :value="option.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supply:node:add']"
          >新增</el-button
        >
      </el-col> -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column
        label="工单编号"
        prop="workOrderNumber"
        width="210"
      ></el-table-column>
      <el-table-column
        label="当前负责企业"
        width="180"
        prop="chargeCompany"
      ></el-table-column>
      <el-table-column label="联系人" prop="contactUser"></el-table-column>
      <el-table-column
        label="联系方式"
        prop="contactUserMobile"
        width="110"
      ></el-table-column>
      <el-table-column
        label="邮箱"
        prop="contactUserEmail"
        width="140"
      ></el-table-column>
      <el-table-column
        label="问题描述"
        width="200"
        prop="workOrderDesc"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="问题类型" prop="workOrderTitle"></el-table-column>
      <el-table-column label="工单状态" width="140">
        <template #default="{ row }">{{
          ORDER_STATUS[row.workOrderStatus]
        }}</template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        width="160"
        prop="createTime"
      ></el-table-column>
      <el-table-column label="结单人" prop="overUserName"></el-table-column>
      <el-table-column
        label="备注"
        width="160"
        show-overflow-tooltip
        prop="remark"
      ></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="160"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="openDetail(scope.row)">详情</el-button>
          <el-button
            v-if="[0, 1].includes(scope.row.workOrderStatus)"
            type="text"
            @click="handleAllocation(scope.row.id)"
            >分配企业</el-button
          >
          <el-button
            v-if="[0, 1].includes(scope.row.workOrderStatus)"
            type="text"
            style="color: red"
            @click="handleVoid(scope.row.id)"
            >作废</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="分配企业"
      :visible.sync="visible"
      width="500px"
      append-to-body
    >
      <el-select
        v-model="selectedCompanyId"
        placeholder="请选择公司"
        style="width: 100%"
        filterable
      >
        <el-option
          v-for="option in companyList"
          :key="option.id"
          :label="option.companyName"
          :value="option.id"
        />
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="!selectedCompanyId"
          type="primary"
          @click="handleConfirm"
          >确 定</el-button
        >
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :visible.sync="drawerVisible"
      :title="currRow.workOrderNumber"
      destroy-on-close
      class="msg-drawer"
      size="50%"
      :before-close="beforeDrawerClose"
    >
      <div class="msg-wrap">
        <div class="msg-content" ref="inner">
          <div
            v-for="msg in msgList"
            :key="msg.time"
            style="margin-bottom: 12px"
            :style="{ 'text-align': msgInRight(msg) ? 'right' : '' }"
          >
            <div class="msg-wrap__top">
              {{ msgInRight(msg) ? "我 |" : `${msg.createBy} |` }}
              {{ msg.createTime }}
            </div>
            <div class="msg-pop">{{ msg.msgContent }}</div>
          </div>
        </div>
        <div class="msg-footer" v-if="[0, 1].includes(currRow.workOrderStatus)">
          <div class="chat-box-input" style="padding: 16px">
            <el-input
              autofocus
              type="textarea"
              class="chat-input"
              resize="none"
              v-model="inputMsg"
            ></el-input>
            <div style="text-align: right">
              <el-button
                type="primary"
                style="
                  width: 64px;
                  height: 32px;
                  border-radius: 2px;
                  margin-top: 8px;
                  text-align: right;
                "
                @click="handleSend"
                >发送</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getOrderList,
  allocationOrder,
  orderSendMsg,
  changeOrderStatus,
  getOrderMsgList,
} from "@/api/system/order";
import companyMixin from "@/mixins/company.js";
import { toggleHtmlScroll } from "@/utils";

const ORDER_STATUS = {
  "-2": "作废",
  "-1": "主动取消",
  0: "待处理",
  1: "处理中",
  2: "用户确认完成",
  3: "系统自动完成",
};

const defaultConfirmOptions = {
  confirmButtonText: "确定",
  cancelButtonText: "取消",
  type: "warning",
};

export default {
  name: "Base",
  mixins: [companyMixin],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      list: [],
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: "",
        keyword: "",
      },
      ORDER_STATUS,
      visible: false,
      currId: "",
      currRow: {},
      selectedCompanyId: "",
      drawerVisible: false,
      msgList: [],
      inputMsg: "",
      timer: null,
    };
  },
  computed: {
    msgInRight() {
      return (msg) => {
        if (msg.createUserId !== this.$store.state.user.id) return false;
        return (
          (msg.msgType === 0 &&
            this.$store.state.user.id === this.currRow.createUserId) ||
          (msg.msgType === 1 &&
            this.$store.state.user.id !== this.currRow.createUserId)
        );
      };
    },
  },
  created() {
    this.getList();
    this.getCompanyList();
  },
  methods: {
    async getMsgList() {
      const lastMsg = this.msgList[this.msgList.length - 1];
      const { data } = await getOrderMsgList({
        workOrderId: this.currRow.id,
        orderNum: lastMsg ? lastMsg.orderNum : null,
      });
      if (!data?.length) return;
      this.msgList.push(...data);
      this.scrollToEnd();
    },

    async handleSend() {
      if (!this.inputMsg) return;
      const { data } = await orderSendMsg({
        msgContent: this.inputMsg,
        workOrderId: this.currRow.id,
      });
      this.msgList.push(data);
      this.scrollToEnd();
      this.inputMsg = "";
    },
    scrollToEnd() {
      this.$nextTick(() => {
        this.$refs.inner.scrollTo({
          top: this.$refs.inner.scrollHeight,
        });
      });
    },
    beforeDrawerClose(done) {
      toggleHtmlScroll();
      clearInterval(this.timer);
      this.timer = null;
      this.msgList = [];
      this.inputMsg = "";
      done();
    },

    openDetail(row) {
      toggleHtmlScroll();
      this.currRow = row;
      this.drawerVisible = true;
      this.timer = setInterval(
        (() => (this.getMsgList(), this.getMsgList))(),
        5000
      );
    },
    async globalConfirmModal({
      title = "提示",
      content = "确定要删除吗？",
      options,
      callbackFunc,
    }) {
      await this.$confirm(
        content,
        title,
        Object.assign({}, defaultConfirmOptions, options)
      );
      typeof callbackFunc === "function" && callbackFunc();
    },
    handleVoid(id) {
      this.globalConfirmModal({
        content: "确定要作废吗？",
        callbackFunc: async () => {
          await changeOrderStatus({
            workOrderId: id,
            workOrderStatus: -2,
          });
          this.$message.success("作废成功");
          this.getList();
        },
      });
    },
    handleAllocation(id) {
      this.currId = id;
      this.visible = true;
    },
    handleCancel() {
      this.visible = false;
      this.selectedCompanyId = "";
    },
    async handleConfirm() {
      await allocationOrder({
        workOrderId: this.currId,
        companyId: this.selectedCompanyId,
      });
      this.$message.success("分配成功");
      this.handleCancel();
      this.getList();
    },
    /** 查询基本信息列表 */
    getList() {
      this.loading = true;
      getOrderList(this.queryParams).then((response) => {
        this.list = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>

<style scoped lang="scss">
.msg-wrap {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  width: 100%;
  height: 100%;

  &__top {
    font-size: 14px;
    color: #8a8c8f;
    margin-bottom: 2px;
  }
}
.msg-content {
  padding: 0 20px;
  flex: 1;
  overflow-y: auto;
}
.chat-box-input {
  box-sizing: border-box;
  border-top: 1px solid #d8d8d8;
}
.msg-pop {
  display: inline-block;
  box-sizing: border-box;
  background: #eff2fc;
  border-top-right-radius: 4px;
  border-bottom-left-radius: 4px;
  padding: 10px 16px 13px;
  text-align: left;
  max-width: 80%;
  word-break: break-all;
}
</style>
<style>
.msg-drawer .el-drawer__body {
  padding: 0 !important;
}
</style>
